import { Login } from '@/api/user'
import Cookies from 'js-cookie'
import { encryptByAES } from "../../utils/secret";

const user = {
  namespaced: true,
  state: {
    // TOKEN: '',
    TOKEN: localStorage.getItem("token") || '',
    userInfo: localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem("userInfo")) : {},
    // set TOKEN(value){
    //     Lockr.set("auth_token", value)
    // },
    // get TOKEN(){
    //     return Lockr.get("auth_token")
    // },
    // userInfo: null,
    userList: []
  },
  mutations: {
    SET_TOKEN(state, data) {
      state.TOKEN = data
    },
    // CLEAR_USER_INFO(state, data){
    //     state.TOKEN = null
    //     Lockr.rm("user_info")
    // },
    SET_USER_INFO(state, data) {
      state.userInfo = data
      // Lockr.set("user_info", data)
    },
    // SET_USER_LIST(state, data){
    //     state.userList = data
    // }
  },
  actions: {
    Login(ctx, data) {
      return new Promise((resolve, reject) => {
        Login(data).then(resp => {
          if (resp.status === 1) {


            if (data.remember) {
              //记住用户名密码、7 天
              Cookies.set("username", encryptByAES(data.username), { expires: 7 })
              Cookies.set("password", encryptByAES(data.password), { expires: 7 })
              Cookies.set("remember", data.remember, { expires: 7 })
            } else {
              Cookies.remove("username")
              Cookies.remove("password")
              Cookies.remove("remember")
            }
            resp.data.password = data.password
            ctx.commit("SET_TOKEN", resp.data.token)
            console.log('resp', resp);
            ctx.commit("SET_USER_INFO", resp.data)
            resolve(resp)
          } else {
            reject(resp)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // GetUserInfo(ctx, data){
    //     return new Promise((resolve, reject) => {
    //         UserAPI.GetUserInfo(data).then(resp => {
    //             if(resp.code === 0){
    //                 ctx.commit("SET_USER_INFO", resp.data)
    //                 resolve(resp)
    //             }else{
    //                 let user_info = Lockr.get("user_info")
    //                 if(user_info){
    //                     ctx.commit("SET_USER_INFO", user_info)
    //                 }
    //             }
    //         }).catch(error => {
    //             reject(error)
    //         })
    //     })
    // },
    Logout(ctx){
      ctx.commit("SET_TOKEN", '')
      ctx.commit("SET_USER_INFO", '')
      localStorage.removeItem("userInfo")
      localStorage.removeItem("token")
    },
    // async GetUserList(ctx, data){
    //     let respList = await UserAPI.GetUserList(data)
    //     ctx.commit("SET_USER_LIST", respList.data)
    // }
  }
}

export default user
